package com.openroom.ui.action;

import java.io.File;
import java.net.URL;

import org.apache.log4j.Logger;
import org.apache.pivot.beans.BXML;
import org.apache.pivot.collections.Map;
import org.apache.pivot.collections.Sequence;
import org.apache.pivot.util.Filter;
import org.apache.pivot.util.Resources;
import org.apache.pivot.util.concurrent.Task;
import org.apache.pivot.util.concurrent.TaskListener;
import org.apache.pivot.wtk.Action;
import org.apache.pivot.wtk.Component;
import org.apache.pivot.wtk.FileBrowserSheet;
import org.apache.pivot.wtk.Label;
import org.apache.pivot.wtk.Meter;
import org.apache.pivot.wtk.Sheet;
import org.apache.pivot.wtk.SheetCloseListener;

import com.openroom.db.DBHelper;
import com.openroom.event.ApplicationEvent;
import com.openroom.event.EventManager;
import com.openroom.event.EventType;
import com.openroom.imageimport.FolderImporter;
import com.openroom.model.Folder;
import com.openroom.model.ModelLocator;
import com.openroom.model.Photograph;
import com.openroom.ui.MainWindow;
import com.openroom.ui.NamespaceHelper;
import com.openroom.ui.ThumbnailMakingTask;
import com.openroom.ui.UIComponent;

public class ImportAction extends Action implements UIComponent {
	private static final Logger LOGGER = Logger.getLogger(ImportAction.class);
	@BXML
	FileBrowserSheet fileBrowserSheet;
	
	private static MainWindow window;
	@BXML
	Sheet dialog;
	@BXML
	Meter meter;

	@BXML
	Label importStatusLabel;
	private static ThumbnailMakingTask task;

	public ImportAction() {
		Action.getNamedActions().put("Import", this);
	}

	@Override
	public void initialize(Map<String, Object> namespace, URL arg1,
			Resources arg2, MainWindow window) {
		NamespaceHelper.initialize(namespace, this);
		this.window = window;
	}

	@Override
	public void perform(Component arg0) {
		fileBrowserSheet
				.setMode(org.apache.pivot.wtk.FileBrowserSheet.Mode.SAVE_TO);
		fileBrowserSheet.setDisabledFileFilter(new Filter<File>() {
			@Override
			public boolean include(File item) {
				if (item.isDirectory())
					return false;
				if (item.getName().toLowerCase().endsWith(".jpg")
						|| item.getName().toLowerCase().endsWith(".jpeg"))
					return false;
				return true;
			}
		});
		fileBrowserSheet.open(this.window, new SheetCloseListener() {
			@Override
			public void sheetClosed(Sheet sheet) {
				Sequence<File> selectedFiles = fileBrowserSheet
						.getSelectedFiles();
				if (selectedFiles.getLength() == 1) {
					File file = selectedFiles.get(0);
					importFolder(file, dialog, window, meter, importStatusLabel);
				}
			}
		});
	}

	public static void importFolder(File file, final Sheet progressDialog,
			MainWindow mainWindow, Meter meter, Label importStatusLabel) {
		if (file == null) {
			return;
		}

		Folder folderByPath = DBHelper.getInstance().getFolderByPath(
				file.getAbsolutePath());
		if (folderByPath != null) {
			LOGGER.warn(file.getAbsolutePath() + " already exists");
			return;
		}
		if (progressDialog != null)
			progressDialog.open(mainWindow);
		Folder importFolder = FolderImporter.importFolder(file, false);
		task = new ThumbnailMakingTask(meter, importStatusLabel, importFolder);
		task.execute(new TaskListener<Void>() {
			@Override
			public void taskExecuted(Task<Void> task) {
				if (progressDialog != null)
					progressDialog.close();
				window.loadSavedDB();
				Photograph photograph = ModelLocator.getInstance()
						.getAllShowingImage().get(0);
				if (photograph != null) {
					ModelLocator.getInstance().setCurrentlySelectedImage(
							photograph);
				}
				EventManager.getInstance().publishEvent(
						new ApplicationEvent(EventType.IMPORT_COMPLETE));
			}

			@Override
			public void executeFailed(Task<Void> task) {
				if (progressDialog != null)
					progressDialog.close();
			}
		});
	}

	public void abortImport() {
		if (task != null)
			task.abort();
	}

}
